<template>
  <a-layout>
    <a-layout-header class="bg-white admin-content-header">
      <div class="col-4 admin-tiao-left">
        <span>{{ $route.name }}</span>
      </div>
      <div class="col-8 text-right">
        <a-button-group style="display:flex;width: 22%;">
          <a-button @click="add" type="primary">
            <a-icon type="plus-circle" />添加文件
          </a-button>
          <el-input size="small" placeholder="请输入查询秘密文件" v-model="value5"></el-input>
        </a-button-group>
        <a-drawer
          :title="title+'文件'"
          placement="right"
          :closable="false"
          @close="visible = false"
          :visible="visible"
          width="450"
        >
          <el-form
            :model="secretfile"
            ref="secretfile"
            :rules="rules"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="名称" prop="name">
              <el-input v-model="secretfile.name"></el-input>
            </el-form-item>
            <el-form-item label="排序">
              <el-input-number v-model="secretfile.paixu"></el-input-number>
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-select v-model="secretfile.type">
                <el-option label="PDF" value="PDF"></el-option>
                <el-option label="PPT" value="PPT"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="使用者" prop="watch">
              <el-select v-model="secretfile.watch">
                <el-option label="用户" value="User"></el-option>
                <el-option label="老师" value="Teacher"></el-option>
                <el-option label="代理商" value="Agent"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标签" prop="tag">
              <el-select
                v-model="tag"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择文章标签"
              >
                <el-option label="乐高积木" value="乐高积木"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="介绍" prop="info">
              <el-input v-model="secretfile.info"></el-input>
            </el-form-item>
            <el-form-item>
              <el-upload
                ref="upload"
                :file-list="fileList"
                :limit=" new Number(1) "
                action="https://jsonplaceholder.typicode.com/posts/"
                :http-request="putimg"
                :on-success="successUpload"
              >
                <el-button type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传文件</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="文件地址" prop="fileurl">
              <el-input v-model="secretfile.fileurl" disabled></el-input>
            </el-form-item>
            <getfile label="选取封面图" :selected="selected1">
              <el-input :value="secretfile.imageurl" disabled></el-input>
            </getfile>
            <el-form-item label="提交">
              <el-button type="primary" @click="submit">提交</el-button>
            </el-form-item>
          </el-form>
        </a-drawer>
      </div>
    </a-layout-header>
    <a-layout-content class="admin-content-table">
      <el-table height="100%" :data="tableDate" style="width: 100%">
        <el-table-column prop="paixu" label="排序" sortable width="100"></el-table-column>
        <el-table-column prop="name" label="名称" width="300"></el-table-column>
        <el-table-column prop="type" label="类型" width="100"></el-table-column>
        <el-table-column prop="watch" label="权限" width="100"></el-table-column>
        <el-table-column prop="lession" label="课程">
          <template slot-scope="scope">
            <el-button type="info" circle v-for="video  in scope.row.lession" :key="video.ID">
              <router-link
                :to="{name: '课程详情', params: { courseId: video.ID }}"
                v-text="video.name.slice(0,1)"
                class="text-white"
              ></router-link>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="tp" label="教师资料">
          <template slot-scope="scope">
            <el-button
              type="info"
              circle
              v-for="video  in scope.row.tp"
              v-text="video.name.slice(0,1)"
              :key="video.ID"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column prop="imageurl" label="配图"></el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <el-button @click="upRow(scope.row)" type="text" size="small">修改</el-button>
            <el-button @click="deleteRow(scope.row.ID)" type="text" size="small">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </a-layout-content>
    <adminContentFooter
      v-bind="{handleSizeChange, handleCurrentChange, currentPage, pagesize,data: tpdata}"
    ></adminContentFooter>
  </a-layout>
</template>

<script>
import OSS from "ali-oss";
import { mapGetters } from "vuex";
import uuid from "uuid/v4";
import getfile from "@/components/admin/getfile.vue";
import adminContentFooter from "../../../components/admin/admin-content-footer";
import {
  asyncdelsecretfile,
  asyncupdatesecretfile,
  asynccreatesecretfile,
  asyncuploadAccess
} from "@/plugins/api.js";
export default {
  name: "secretfile",
  data() {
    return {
      pagesize: 20,
      currentPage: 1,
      loading3: false,
      tag: [],
      allkechneg: [],
      value5: "",
      paths: [
        {
          name: "秘密文件",
          path: "/secretfile/index"
        }
      ],
      secretfile: {
        ID: "",
        fileurl: "",
        name: "",
        imageurl: "",
        type: "PDF",
        watch: "Teacher",
        TgtUri: "",
        info: "",
        tag: "",
        paixu: 1
      },
      visible: false,
      fileList: [],
      rules: {
        fileurl: [
          { required: true, message: "文件地址不能为空", trigger: "blur" }
        ]
      },
      title: "添加"
    };
  },
  computed: {
    ...mapGetters(["getSecretfile", "getCourse", "getTpdata"]),
    tableDate() {
      const { tpdata, getCourse, getTpdata, pagesize, currentPage } = this;
      const data = tpdata.slice(
        (currentPage - 1) * pagesize,
        currentPage * pagesize
      );
      return data.map(v => {
        const lession = getCourse.filter(vo => {
          const [l] = vo.lession;
          if (l && l.type === "vector" && l.secretfileID == v.ID) return true;
        });
        const tp = getTpdata.filter(vo => {
          const { fileurl } = vo;
          return fileurl === v.TgtUri;
        });
        return {
          ...v,
          lession,
          tp
        };
      });
    },
    tpdata() {
      const { getSecretfile, value5 } = this;
      return getSecretfile.filter(v => {
        if (value5) {
          return v.name ? v.name.includes(value5) : false;
        }
        return true;
      });
    }
  },
  methods: {
    handleSizeChange(val) {
      this.pagesize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    async submit() {
      this.$refs["secretfile"].validate(async valid => {
        if (valid) {
          try {
            if (!this.secretfile.ID) {
              await asynccreatesecretfile(this.secretfile);
            } else {
              await asyncupdatesecretfile(this.secretfile);
            }
            this.$store.dispatch("actionSecretfile");
            this.visible = false;
            this.$message({
              type: "success",
              message: `${this.title}成功!`
            });
          } catch (err) {
            this.$message({
              type: "error",
              message: `${this.title}失败!`
            });
          }
        } else {
          return false;
        }
      });
    },
    async deleteRow(ID) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await asyncdelsecretfile({ ID });
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.$store.dispatch("actionSecretfile");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    add() {
      this.secretfile = {
        ID: "",
        fileurl: "",
        name: "",
        imageurl: "",
        type: "PDF",
        watch: "Teacher",
        TgtUri: "",
        paixu: 1
      };
      this.fileList = [];
      this.visible = true;
      this.title = "添加";
    },
    upRow(index) {
      this.secretfile = JSON.parse(JSON.stringify(index));
      if (this.secretfile.tag === null) {
        this.tag = [];
      } else {
        this.tag = this.secretfile.tag.split(",");
      }
      this.fileList = [];
      this.visible = true;
      this.title = "修改";
    },
    successUpload(e) {
      console.log(e);
    },
    async putimg(e) {
      let option = await this.getcreds();
      let client = new OSS(option);
      // object表示上传到OSS的名字，可自己定义
      // file浏览器中需要上传的文件，支持HTML5 file 和 Blob类型
      try {
        const type = e.file.name.split(".");
        const name = `${uuid()}.${type[type.length - 1]}`;
        await client.put(`${decodeURIComponent("input/")}${name}`, e.file);
        this.secretfile.fileurl = `https://hterobot-pdf.oss-cn-beijing.aliyuncs.com/input/${name}`;
        this.secretfile.TgtUri = `https://hterobot-pdf.oss-cn-beijing.aliyuncs.com/output/${name}`;
      } catch (err) {
        console.log(err);
      }
    },
    async getcreds() {
      let creds = await asyncuploadAccess();
      return {
        region: "oss-cn-beijing",
        bucket: "hterobot-pdf",
        stsToken: creds.securityToken,
        accessKeyId: creds.accessKeyId,
        accessKeySecret: creds.accessKeySecret
      };
    },
    selected1(v) {
      this.secretfile.imageurl = v;
    }
  },
  components: {
    getfile,
    adminContentFooter
  }
};
</script>

